package com.sam.im.heiqun.uis.activities;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.NearbyEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.NearbyAdapter;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class NearbyActivity extends BaseSwipeBackActivity implements AMapLocationListener {

    private static final int SDK_PERMISSION_REQUEST = 127;

    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.nonearby)
    TextView tvnonearby ;
    private NearbyAdapter adapter ;
    private List<NearbyEntivity.ListBean> nearbys = new ArrayList<>();
    private List<NearbyEntivity.ListBean> nearbyAlls = new ArrayList<>();
    private int pageNo = 1 ;

    private PopupMenu popupMenu;
    private Menu menu;

    @Override
    public int getContentViewId() {
        return R.layout.activity_nearby;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.near_person);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//          showProgress("正在搜索附近的人");
          adapter = new NearbyAdapter(this,nearbys);
          recyclerview.setAdapter(adapter);
          recyclerview.setLayoutManager(new LinearLayoutManager(this));
          String lat = ToolsUtils.getSf(this, "lat");
          String lnt = ToolsUtils.getSf(this, "lnt");
          showProgress(getResources().getString(R.string.now_get_location));
          getPersimmions();
        right.setVisibility(View.VISIBLE);
        initMenu();
       /* if (StringUtils.isEmpty(lat)||StringUtils.isEmpty(lnt)){
            showToast("无法获取您的当前位置");
        }else {

        }*/
    }
    private void getnearby(String lat ,String lnt) {
        PGService.getInstance().getnearby(lat,lnt,pageNo+"", ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<NearbyEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
            }

            @Override
            public void onNext(NearbyEntivity nearbyEntivity) {
                if (nearbyEntivity != null) {
                    Collections.sort(nearbyEntivity.getList(), new  Comparator<NearbyEntivity.ListBean>() {

                        @Override
                        public int compare(NearbyEntivity.ListBean o1, NearbyEntivity.ListBean o2) {
                            String longitude1 = o1.getLongitude();
                            String latitude1 = o1.getLatitude();
                            String latitude2 = o2.getLatitude();
                            String longitude2 = o2.getLongitude();
                            String mylat = ToolsUtils.getSf(NearbyActivity.this, "lat");
                            String mylnt = ToolsUtils.getSf(NearbyActivity.this, "lnt");
                            Double mylat1 = Double.valueOf(mylat);
                            Double mylnt1 = Double.valueOf(mylnt);
                            Double lat1 = Double.valueOf(latitude1);
                            Double lnt1 = Double.valueOf(longitude1);
                            Double lat2 = Double.valueOf(latitude2);
                            Double lnt2 = Double.valueOf(longitude2);
                            double distance1 = ToolsUtils.getDistance(mylnt1, mylat1, lnt1, lat1);
                            double distance2 = ToolsUtils.getDistance(mylnt1, mylat1, lnt2, lat2);
                            return (int)(distance1-distance2);
                        }
                    });
                    nearbyAlls.addAll(nearbyEntivity.getList());
                    nearbys.addAll(nearbyEntivity.getList());
                    adapter.notifyDataSetChanged();
                }
                if (nearbys.size()==0){
                    recyclerview.setVisibility(View.GONE);
                    tvnonearby.setVisibility(View.VISIBLE);
                }else {
                    recyclerview.setVisibility(View.VISIBLE);
                    tvnonearby.setVisibility(View.GONE);
                }
                hideProgress();
            }
        });
    }

    @OnClick({ R.id.pre_v_back, R.id.right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back: {
                finish();
                break;
            }
            case R.id.right: {
                popupMenu.show();
                break;
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                amapLocation.getLatitude();//获取纬度
                amapLocation.getLongitude();//获取经度
                amapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                Log.i("info","定位成功=="+amapLocation.getLatitude()+"  "+amapLocation.getLongitude());
                locationClient.stopLocation();
                HashMap<String,String> map = new HashMap<>();
                map.put("lat",amapLocation.getLatitude()+"");
                map.put("lnt",amapLocation.getLongitude()+"");
                ToolsUtils.saveSf(NearbyActivity.this,map);
                hideProgress();
                showProgress(getResources().getString(R.string.now_down));
                getnearby(amapLocation.getLatitude()+"",amapLocation.getLongitude()+"");
                PGService.getInstance().uplocation(amapLocation.getLatitude()+"",amapLocation.getLongitude()+"",ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {

                    }
                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        if (validateEntivity != null) {
                            Log.i("info","位置提交成功=="+validateEntivity.getInfo());
                        }
                    }
                });
            } else {
                showProgress("位置信息获取失败");
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + amapLocation.getErrorCode() + ", errInfo:"
                        + amapLocation.getErrorInfo());
            }
        }
    }

//    public AMapLocationClient mlocationClient =null ;
//    //定位
//    public void getlocation() {
//
//        //声明mLocationOption对象
//        mlocationClient = new AMapLocationClient(this);
////初始化定位参数
//        mLocationOption = new AMapLocationClientOption();
////设置定位监听
//        mlocationClient.setLocationListener(this);
////设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
////设置定位间隔,单位毫秒,默认为2000ms
//        mLocationOption.setInterval(2000);
////设置定位参数
//        mlocationClient.setLocationOption(mLocationOption);
//// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
//// 注意设置合适的定位时间的间隔（最小间隔支持为1000ms），并且在合适时间调用stopLocation()方法来取消定位请求
//// 在定位结束后，在合适的生命周期调用onDestroy()方法
//// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
////启动定位
//         mlocationClient.startLocation();
//    }

    @Override
    protected void onDestroy() {
        hideProgress();
        nearbys.clear();
        super.onDestroy();
    }


    private AMapLocationClient locationClient;//高德定位类
    private AMapLocationClientOption mLocationOption;
    private void startLocation() {
        if (locationClient == null) {
            //初始化定位
            locationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            locationClient.setLocationListener(this);
//            new AMapLocationListener() {
//                @Override
//                public void onLocationChanged(AMapLocation aMapLocation) {
//                    //经度
//                    mylongitude = aMapLocation.getLongitude();
//                    //纬度
//                    mylatitude = aMapLocation.getLatitude();
//
//
//
//                    /*//地址信息
//                address = aMapLocation.getAddress();
//                //城市
//                city = aMapLocation.getCity();
//                //省份
//                province = aMapLocation.getProvince();
//                //街道
//                street = aMapLocation.getStreet();
//                //区
//                district = aMapLocation.getDistrict();
//                //位置语意信息
//                description = aMapLocation.getDescription();
//                altitude = aMapLocation.getAltitude();
//                //街道号
//                streetNum = aMapLocation.getStreetNum();
//                //楼层信息
//                floor = aMapLocation.getFloor();
//                //经度
//                longitude = aMapLocation.getLongitude();
//                //纬度
//                latitude = aMapLocation.getLatitude();
//                //poiname
//                poiName = aMapLocation.getPoiName();*/
//                }
//            });
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            locationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            locationClient.startLocation();//启动定位
        }
    }

    @TargetApi(23)
    protected void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            // 读写权限
            int pos = 0 ;
            if (addPermission(permissions, Manifest.permission.ACCESS_FINE_LOCATION)) {
                pos ++ ;
            }
            if (addPermission(permissions, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                pos ++ ;
            }
            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }else {
                startLocation();
            }
        }else {
            //不用动态申请权限
            startLocation();
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                //拒绝了也是可以强行提示的，不过如果再也不提示的情况还没处理
                permissionsList.add(permission);
                return false;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                Map<String, Integer> perms = new HashMap<String, Integer>();
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                try {
                    int isgre = 0 ;
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        isgre ++;
                    }
                    if (2 <= isgre){
                        startLocation();
                    }else {
                        Toast.makeText(this, getResources().getString(R.string.no_pawr_nouse), Toast.LENGTH_SHORT)
                                .show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    public void initMenu() {

        popupMenu = new PopupMenu(this, right);
        menu = popupMenu.getMenu();
        // 通过XML文件添加菜单项
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu_nearby, menu);

        // 监听事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {

                    case R.id.look_man://
                    {
                        nearbys.clear();
                        if (null!=nearbyAlls && nearbyAlls.size() > 0){
                            for (int i = 0; i < nearbyAlls.size(); i++) {
                                NearbyEntivity.ListBean listBean = nearbyAlls.get(i);
                                if (null!=listBean && "男".equals(listBean.getSex())){
                                    nearbys.add(listBean);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    }
                    case R.id.look_woman: {//
                        nearbys.clear();
                        if (null!=nearbyAlls && nearbyAlls.size() > 0){
                            for (int i = 0; i < nearbyAlls.size(); i++) {
                                NearbyEntivity.ListBean listBean = nearbyAlls.get(i);
                                if (null!=listBean && "女".equals(listBean.getSex())){
                                    nearbys.add(listBean);
                                }
                            }
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    }
                    case R.id.look_all: {//
                        nearbys.clear();
                        if (null!=nearbyAlls && nearbyAlls.size() > 0){
                            nearbys.addAll(nearbyAlls);
                            adapter.notifyDataSetChanged();
                        }
                        break;
                    }

                    default:
                        if (nearbys.size()==0){
                            recyclerview.setVisibility(View.GONE);
                            tvnonearby.setVisibility(View.VISIBLE);
                        }else {
                            recyclerview.setVisibility(View.VISIBLE);
                            tvnonearby.setVisibility(View.GONE);
                        }
                        break;
                }
                return false;
            }
        });
    }



}
